// import {
//   getBallCourtInfoByPointById
// } from "../../../api/home/home.js";
Page({

  /**
   * 页面的初始数据
   */
  data: {
    lat: 39.908692,
    lng: 116.397477,
    scale: 12,
    markers: [],
    margintop: "",
    funcrowheight: "",
    mapChange: false,
    showPopup: false,
    ballCourtInfo: {},
    animationClass: '', // 过渡效果类名
    avatarUrl: "/images/nologin.png",
    //腾讯地图key（根据经纬度获取城市名）
    txKey: "2NSBZ-W6665-L2SIQ-I6TY2-U3L6O-2EFIH",
    //高德地图key（根据code获取城市天气）
    gdKey: "7759d4cb79251db80ff0d57518266bda",
    //温度
    temperature: "",
    //天气
    weather: "",
    localUrl: "/images/dw.png",
    localUrlDisplay: "none",
    city: "",
    closeDisplay: "none",
    closeDisplaySearch: "none",
    coverDisplay: "block",
    isLoad:0,
    qiehuan:true,
    regionChanged: false,     // 地图区域是否发生变化的标志
    hospitalsObject:{},
    loadingFlag:false,
    showSearch:false
  },

    /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {

    const {
      height,
      top
    } = wx.getMenuButtonBoundingClientRect();
    // 定义功能菜单行与胶囊对其
    this.setData({
      margintop: top,
      funcrowheight: height
    })
    this.getBallCourtList()

    //更新local图标
    // const mapCtx = wx.createMapContext('map')
    // mapCtx.setLocMarkerIcon({
    // iconPath:'/images/zx.png',
    // })
  },
  onShow() {
    console.log("index, show!")
    this.refreshLocal()
    this.onlineOrOffline()
    this.setData({
      showPopup: false,
      closeDisplay: "none",
      coverDisplay: "block"
    })
  },

  onMarkerTap(e) {
    this.setData({
      hospitalsObject: {}
    })
    let that = this
    console.log(e);
    let result = this.data.markers.find(item => item.id === e.detail.markerId);
    that.setData({
      showPopup: true,
      closeDisplay: "block",
      coverDisplay: "none",
      hospitalsObject: result
    })
  },
  onClosePopup() {
    this.setData({
      showPopup: false,
      closeDisplay: "none",
      coverDisplay: "block"
    })
  },
  onClosePopupSearch(){
    this.setData({
      showSearch: false,
      closeDisplaySearch: "none",
      coverDisplay: "block"
    })
  },

  getBallCourtList() {
    let that = this
    this.myMap = wx.createMapContext('map')
    console.log('用户：');
    console.log(this.myMap);
    wx.getLocation({
      type: 'gcj02',
      success: function (res) {
        wx.setStorageSync('has_get_location', true);
        console.log('用户已授权位置权限,经纬度：' + res.longitude, res.latitude);
        that.setData({
          lat: res.latitude,
          lng: res.longitude
        })
        //根据经纬度获取城市名
        that.getCityFromCoordinates(res.latitude, res.longitude, that.data.txKey).then((result) => {
          const city = result.data.result.address_component.city;
          that.setData({
            city: city
          })
          that.getCityWeatherFromCode(result.data.result.ad_info.adcode, that.data.gdKey).then((weatherResult) => {
            console.log(city)
            console.log(weatherResult)
            that.setData({
              temperature: weatherResult.data.lives[0].temperature + "℃",
              weather: weatherResult.data.lives[0].weather,
              localUrlDisplay: "block"
            })
          })
        })

 
      },
      fail: function () {
        wx.setStorageSync('has_get_location', true);
        console.log("获取地理位置失败")
        that.setData({
          lat: 39.908692,
          lng: 116.397477
        })
        //根据经纬度获取城市名
        that.getCityFromCoordinates(that.data.lat, that.data.lng, that.data.txKey).then((result) => {
          const city = result.data.result.address_component.city;
          that.setData({
            city: city
          })
          that.getCityWeatherFromCode(result.data.result.ad_info.adcode, that.data.gdKey).then((weatherResult) => {
            console.log(city)
            console.log(weatherResult)
            that.setData({
              temperature: weatherResult.data.lives[0].temperature + "℃",
              weather: weatherResult.data.lives[0].weather,
              localUrlDisplay: "block"
            })
          })
        })
        let res = {
          latitude: that.data.lat, 
          longitude: that.data.lng
        }
 
      }
    })

    setTimeout(()=>{
      this.getHospitalLoacal(this.data.lng,this.data.lat)
    },500)

  },
  //获取当前地图中心的经纬度
  toSearchPage: function () {
    this.myMap.getCenterLocation({
      success: function (res) {
        console.log(" mid ")
        console.log(res.longitude)
        console.log(res.latitude)
      }
    })
  },
  toSearch(){
    this.setData({
      showSearch:true,
      closeDisplaySearch: "block",
      coverDisplay: "none",
    })
  },
  closeShowSearch(){
    this.setData({
      showSearch:false,
      closeDisplaySearch: "none",
      coverDisplay: "block",
    })
  },

  onlineOrOffline() {
    let userInfo = wx.getStorageSync('userInfo')
    if (userInfo == null || userInfo == undefined || userInfo == '') {
      // userInfo为空
      this.setData({
        avatarUrl: "/images/nologin.png"
      })
    } else {
      // userInfo非空
      this.setData({
        avatarUrl: userInfo.avatarUrl
      })
    }
  },

  toggleMapLayer() {
    this.setData({
      mapChange: !this.data.mapChange
    })
  },

  login() {
    let userInfo = wx.getStorageSync('userInfo')
    if (userInfo == null || userInfo == undefined || userInfo == '' || userInfo.token == undefined) {
      wx.navigateTo({
        url: '/pages/login/login',
      })
    } else {
      wx.switchTab({
        url: '/pages/tabbar/mine/mine',
      })
    }
  },
  getCityFromCoordinates(latitude, longitude, txKey) {
    return new Promise((resolve, reject) => {
      const url = `https://apis.map.qq.com/ws/geocoder/v1/?location=${latitude},${longitude}&key=${txKey}`;
      wx.request({
        url: url,
        success: function (res) {
          if (res.data.status === 0) {
            resolve(res);
          } else {
            reject(res.data.message);
          }
        },
        fail: function (res) {
          reject(res.errMsg);
        }
      });
    });
  },
  getCityWeatherFromCode(code, gdKey) {
    return new Promise((resolve, reject) => {
      const url = `https://restapi.amap.com/v3/weather/weatherInfo?city=${code}&key=${gdKey}`;
      wx.request({
        url: url,
        success: function (res) {
          if (res.data.status === "1") {
            resolve(res);
          } else {
            reject(res.data.message);
          }
        },
        fail: function (res) {
          reject(res.errMsg);
        }
      });
    });
  },
  refreshLocal(){
    let that = this
    wx.getSetting({
      success(res) {
        if (res.authSetting['scope.userLocation']) {
          // 用户已授权，可以再次调用 wx.getLocation
          that.getBallCourtList()
          that.setData({
            scale: 12,
            lat: that.data.lat,
            lng: that.data.lng
          })
        } else {
          that.setData({
            lat: 39.908692,
            lng: 116.397477
          })
          //根据经纬度获取城市名
          that.getCityFromCoordinates(that.data.lat, that.data.lng, that.data.txKey).then((result) => {
            const city = result.data.result.address_component.city;
            that.setData({
              city: city
            })
            that.getCityWeatherFromCode(result.data.result.ad_info.adcode, that.data.gdKey).then((weatherResult) => {
              console.log(city)
              console.log(weatherResult)
              that.setData({
                temperature: weatherResult.data.lives[0].temperature + "℃",
                weather: weatherResult.data.lives[0].weather,
                localUrlDisplay: "block"
              })
            })
          })
          let res = {
            latitude: that.data.lat, 
            longitude: that.data.lng
          }
  
          // 用户未授权，需要引导用户去设置页面开启授权
          if (wx.getStorageSync('has_get_location')) {
            wx.showModal({
              content:"需要获取您的地理位置，请在设置中开启允许访问地理位置",
              success(res){
                if (res.confirm) {
                  wx.openSetting({
                    success(res) {
                      if (res.authSetting['scope.userLocation']) {
                        // 用户在设置页面开启了授权，可以再次调用 wx.getLocation
                        that.getBallCourtList()
                        that.setData({
                          scale: 12,
                          lat: that.data.lat,
                          lng: that.data.lng
                        })
                      } else {
                        // 用户仍然未授权，需要处理授权失败的情况
                        that.getBallCourtList()
                      }
                    }
                  })
                }
              }
            })
          }
        }
      }
    })

  },
  goCourtPage(){
    wx.navigateTo({
      url: '/pages/court/court?ballCourtInfo='+JSON.stringify(this.data.ballCourtInfo),
    })
  },
  qiehuan(){
    wx.showLoading()
    setTimeout(()=>{
      this.setData({
        qiehuan: !this.data.qiehuan
      })
      wx.hideLoading()
    },500)

    console.log(this.data.qiehuan)
    console.log(this.data.markers)
  },
  onMapRegionChange: function (e) {
    if (e.type === 'end') {
      this.setData({
        regionChanged: false
      });
      this.getHospitalLoacal(e.detail.centerLocation.longitude, e.detail.centerLocation.latitude);
    }
  },
  getHospitalLoacal(lng,lat){
    this.myMap = wx.createMapContext('map')
    this.myMap.removeMarkers()

    this.setData({
      markers: [],
      loadingFlag:true
    });
    setTimeout(()=>{
    console.log("搜索医院···")
     // 使用腾讯地图API进行关键词搜索
     wx.request({
      url: 'https://apis.map.qq.com/ws/place/v1/search',
      data: {
        keyword: '医院',  // 搜索关键词为“医院”
        boundary: 'nearby('+lat+','+lng+',1000,1)',  // 在深圳市范围内搜索
        key: this.data.txKey,
        page_size: 20,
        page_index: 1
      },
      success: res => {
        if (res.data.status === 0) {
          let hospitals = res.data.data.map(item => {
            const timestamp = new Date().getTime();
            const randomNum = Math.floor(Math.random() * 1000); // 生成一个 0 到 999 之间的随机数
            const randomId = Number(timestamp + randomNum);
            return {
              id: randomId,
              markerId: randomId,
              longitude: item.location.lng,
              latitude: item.location.lat,
              title: item.title,
              address: item.address,
              category: item.category,
              tel: item.tel,
              distance: item._distance,
              iconPath: '/images/yiyuan.png', // 自定义标记的图标
              width: 35,
              height: 35
            };
          });
          this.setData({
            markers: hospitals,
            loadingFlag:false
          });
        } else {
          console.error('地图API请求失败:', res.data.message);
        }
      },
      fail: error => {
        console.error('地图API请求失败:', error);
      }
    });
    },500)
  },
    // 拨打电话
    makePhoneCall() {
      console.log(this.data.hospitalsObject.tel)
      let arr = this.data.hospitalsObject.tel.split(";")
      wx.showActionSheet({
        itemList: arr,
        success: function(res) {
          console.log(res)

            wx.makePhoneCall({
              phoneNumber: arr[res.tapIndex]
            });

        }
      });
    },
    // 打开地图
    openLocation() {
      let that = this
      wx.openLocation({
        latitude: Number(that.data.hospitalsObject.latitude),
        longitude: Number(that.data.hospitalsObject.longitude),
        name: that.data.hospitalsObject.title,
        address: that.data.hospitalsObject.address
      })
    },
})